<template>
  <el-container class="main-container">
    <el-aside class="aside" style="width:225px">
      <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" default-expand-all
        :expand-on-click-node="false" background-color="#f0f2f5" text-color="#333" highlight-current>
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <div>
              <span v-if="!data.children" class="dot"></span>
              <span>{{ node.label }}</span>
            </div>
            <div style="margin-right:15px">
              <span class="count">{{ data.Count }}</span>
            </div>
            <div style="margin-right:15px" v-show="!data.Id">
              <el-button type="primary" link @click="editClass">编辑</el-button>
            </div>
          </span>
        </template>
      </el-tree>
    </el-aside>
    <el-container class="content-container">
      <el-header class="header">
        <div class="search-bar">
          <el-date-picker :popper-class="color === 'night' ? 'nightClass' : ''" v-model="searchForm.StartTime"
            type="datetimerange" :shortcuts="shortcuts" value-format="YYYY-MM-DD HH:mm:ss" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" class="date-picker" />
          <el-input v-model="searchForm.Descp" placeholder="请输入标题,支持模糊搜索" class="input" />
          <!-- <el-checkbox
            v-model="searchForm.Status"
            @change="searchData()"
            :true-label="1"
            :false-label="2"
            class="checkbox"
            >只显示我创建的收藏</el-checkbox
          > -->
          <el-button type="primary" @click="searchData">搜索</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </div>
      </el-header>
      <el-main>
        <div class="table-header">
          <el-button size="large" type="primary" @click="handleAdd">添加收藏</el-button>
        </div>
        <el-table :data="tableData" class="table" stripe>
          <el-table-column type="index" :index="index => (pageNum - 1) * pageSize + index + 1" width="80" label="序号" />
          <el-table-column prop="Title" label="标题" :show-overflow-tooltip="{ popperClass: 'custom-tooltip' }" />
          <el-table-column prop="UserID" label="用户" width="120" />
          <el-table-column prop="ClassID" label="分类" width="120" :formatter="formatClassName" />
          <el-table-column prop="CreateTime" label="发布时间" width="180">
            <template #default="{ row }">
              <span>{{ parseTime(row.CreateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="UpdateTime" label="更新时间" width="180">
            <template #default="{ row }">
              <span>{{ parseTime(row.UpdateTime) }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="ContentLink" label="内容" :show-overflow-tooltip="{ popperClass: 'custom-tooltip' }" /> -->
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.row)"
                :disabled="scope.row.UserID !== UserID">修改</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)"
                :disabled="scope.row.UserID !== UserID">删除</el-button>
              <el-button type="success" @click="handlePreview(scope.row)">预览</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-size="pageSize" background layout="prev, pager, next" :total="total" />
        </div>
      </el-main>
    </el-container>

    <KnowledgeBaseDialog :classList="classList" :Action="Action" :joinType="2" :dialogForm="dialogForm"
      :dialogVisible="dialogVisible" @closeDialog="closeDialog" @submitDialog="submitDialog" />
    <collectDialog :nodeData="treeData" :dialogVisible="dialogClass" @closeDialogClass="closeDialogClass"
      @GetUserChatCollectClass="GetUserChatCollectClass" />
  </el-container>
</template>

<script>
import { ElMessage, ElMessageBox, formatter } from "element-plus";
import { defineComponent, ref, onMounted, nextTick } from "vue";
import KnowledgeBaseDialog from "./components/KnowledgeBaseDialog.vue";
import collectDialog from "./components/collectDialog.vue";
import {
  Location,
  Document,
  Menu as IconMenu,
  Setting,
} from "@element-plus/icons-vue";
import { connrequest, uploadfile } from "../api/connrequest";
import { parseTime } from "../utils/index";

export default defineComponent({
  name: "KnowledgeBase",
  components: {
    KnowledgeBaseDialog,
    collectDialog,
    Location,
    Document,
    IconMenu,
    Setting,
  },
  setup() {
    const color = ref(localStorage.getItem('isNightMode') || 'night');
    const shortcuts = [
      {
        text: "最近一周",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setDate(start.getDate() - 7);
          return [start, end];
        },
      },
      {
        text: "最近一个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 1);
          return [start, end];
        },
      },
      {
        text: "最近三个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 3);
          return [start, end];
        },
      },
    ];
    // ClassID转Name
    function formatClassName(row, column, cellValue) {
      const match = treeData.value[0].children.find(item => item.Id === cellValue);
      return match ? match.Name : '-';
    }

    // 树形菜单数据
    const treeData = ref([{ Name: "所有收藏", children: [] }]);
    const defaultProps = ref({ label: "Name", children: "children" });

    const handleNodeClick = (data) => {
      searchData({ MainClassID: data.Id === 0 ? "" : data.Id });
    };

    // 搜索表单数据
    const searchForm = ref({ StartTime: "", Descp: "", Status: 2 });
    const pageNum = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 搜索方法
    const searchData = async (searchObj = {}) => {
      try {
        const data = {
          Paging: {
            QueryPageNo: pageNum.value,
            QueryPageLength: pageSize.value,
          },
          Filter: {
            Status: 2,
            ...searchForm.value,
            StartTime: searchForm.value.StartTime?.[0] || "",
            EndTime: searchForm.value.StartTime?.[1] || "",
            ...searchObj,
          },
        };
        const res = await connrequest("GetUserChatCollect", data);
        if (res && res.Status.StatusCode === 0) {
          //同步更新左侧树数据
          GetUserChatCollectClass();
          //处理数据，添加Class字段
          tableData.value = processData(res.Data);
          total.value = res.Paging.TotalCount || 0;
        } else {
          tableData.value = [];
          total.value = 0;
        }
      } catch (error) {

        tableData.value = [];
        total.value = 0;
        ElMessage.error("获取收藏列表失败");

      }
    };

    const reset = () => {
      searchForm.value = { StartTime: "", Descp: "", Status: 2 };
      searchData();
    };

    const tableData = ref([]);
    const handleSizeChange = (val) => {
      pageSize.value = val;
      searchData();
    };
    const handleCurrentChange = (val) => {
      pageNum.value = val;
      searchData();
    };

    const dialogVisible = ref(false);
    const openDialog = () => {
      dialogVisible.value = true;
    };
    const closeDialog = () => {
      dialogVisible.value = false;
    };
    const Action = ref(1);
    const dialogForm = ref({
      Title: "",
      ClassID: "",
      Property: 1,
      ContentLink: "",
    });
    const UUID = ref("");

    // 弹窗提交数据
    const submitDialog = async (submitdata, Action) => {
      const blob = new Blob([submitdata.ContentLink], { type: "text/plain" });
      const file = new File([blob], "test.txt", { type: "text/plain" });
      let formData = new FormData();
      formData.append("CmdCode", "UploadFileToTmp");
      if (Action === 2) {
        formData.append("UUID", UUID.value);
      }
      formData.append("file", file);
      const fileUUID = await uploadfile(formData);
      try {
        const data = {
          Data: {
            Action,
            Detail: {
              UserID: sessionStorage.getItem("Name"),
              ...submitdata,
              ContentLink: fileUUID.Data.UUID,
            },
          },
        };
        const res = await connrequest("EditUserChatCollect", data);
        if (res && res.Status.StatusCode === 0) {
          searchData();
          ElMessage.success(Action.value === 1 ? "添加成功" : "修改成功");
          dialogVisible.value = false;
        } else {
          ElMessage.error(res.Status.Msg2Client);
        }
      } catch (error) {
        ElMessage.error(error.Status.Msg2Client);
      }
    };

    const handleAdd = () => {
      Action.value = 1;

      dialogForm.value = {
        Title: "",
        ClassID: classList.value?.[0]?.Class ?? "",
        Property: 2,
        ContentLink: "",
      };
      nextTick(() => openDialog());
    };

    const handleEdit = async (row) => {
      UUID.value = row.ContentLink;
      Action.value = 2;
      const fileUrl = `/user_chat_collect/${row.ContentLink}`;
      const response = await fetch(fileUrl);
      if (!response.ok) {
        ElMessage.error("收藏获取失败");
        return;
      }
      const text = await response.text();
      dialogForm.value = { ...row, ContentLink: text };
      openDialog();
    };

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm("确定删除该收藏吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const data = {
          Data: {
            Action: 3,
            Detail: { UserID: sessionStorage.getItem("Name"), ...row },
          },
        };
        const res = await connrequest("EditUserChatCollect", data);
        if (res && res.Status.StatusCode === 0) {
          searchData();
          ElMessage.success("删除成功");
        } else {
          ElMessage.error("删除失败");
        }
      } catch (error) {
        if (error !== "cancel") ElMessage.error("删除收藏请求错误");
      }
    };

    const handlePreview = async (row) => {
      Action.value = 4;
      const fileUrl = `/user_chat_collect/${row.ContentLink}`;
      const response = await fetch(fileUrl);
      if (!response.ok) {
        ElMessage.error("收藏获取失败");
        return;
      }
      const text = await response.text();
      dialogForm.value = { ...row, ContentLink: text };
      openDialog();
    };
    // const handlePreview =async (row) =>{
    //   try {
    //     const fileUrl = `/user_chat_collect/${row.ContentLink}`;
    //     // 发起请求以获取内容
    //     const response = await fetch(fileUrl);
    //     if (!response.ok) {
    //       ElMessage.error("企业收藏获取失败");
    //       return;
    //     }
    //     // 获取文本内容
    //     const text = await response.text();
    //     // 确保 HTML 内容包含字符编码声明
    //     // 如果服务器未正确设置 Content-Type，可以手动添加 <meta> 标签
    //     const htmlWithMeta = `
    //       <!DOCTYPE html>
    //       <html lang="zh-CN">
    //       <head>
    //         <meta charset="UTF-8">
    //         <title>标题：${row.Title}</title>
    //       </head>
    //       <body>
    //         ${text}
    //       </body>
    //       </html>
    //     `;
    //     // 创建一个 Blob 对象，并指定 MIME 类型为 text/html; charset=utf-8
    //     const blob = new Blob([htmlWithMeta], { type: 'text/html; charset=utf-8' });
    //     // 创建一个 URL 对象
    //     const blobUrl = URL.createObjectURL(blob);
    //     // 打开一个新窗口
    //     const newWindow = window.open(blobUrl, '_blank');
    //     // 立即将新窗口的 opener 设置为 null，防止其通过 window.opener 访问原始窗口
    //     if (newWindow) {
    //       newWindow.opener = null;
    //     }
    //     // 可选：在适当的时机释放 Blob URL 以节省资源
    //     // 例如，可以在新窗口关闭时调用 URL.revokeObjectURL(blobUrl)
    //     // 需要额外逻辑来跟踪和管理 Blob URL 的生命周期
    //   } catch (error) {
    //     console.error("预览时发生错误:", error);
    //     ElMessage.error("预览时发生错误");
    //   }
    // };

    const classList = ref([]);
    //定义一个变量接收res.Data
    const mapping = ref([]);
    const GetUserChatCollectClass = async (searchObj = {}) => {
      const data = {
        Filter: {
          Status: 2,
          ...searchForm.value,
          StartTime: searchForm.value.StartTime?.[0] || "",
          EndTime: searchForm.value.StartTime?.[1] || "",
          ...searchObj,
        },
      };
      const res = await connrequest("GetUserChatCollectClass", data);
      treeData.value[0].children = res.Data;

      //将获取到的数据传递给变量以供转化成树结构做关联查询
      mapping.value = res.Data
      // 用于对话框的下拉框填充的数据
      classList.value = res.Data

    };

    const UserID = sessionStorage.getItem("Name");
    onMounted(() => {
      GetUserChatCollectClass();
      searchData();
    });

    // 将获取到的分类信息转化成树状结构
    const buildTree = (data) => {
      const map = {};
      const roots = [];

      // 初始化每个节点的 Children 数组
      data.forEach((item) => {
        map[item.ID] = { ...item, children: [] };
      });

      // 构建树关系
      data.forEach((item) => {
        if (item.ParentID === 0) {
          roots.push(map[item.ID]);
        } else {
          if (map[item.ParentID]) {
            map[item.ParentID].children.push(map[item.ID]);
          }
        }
      });

      return roots;
    };
    // 处理数据table表的数据，通过table.ID=== classList.ID添加 Class 字段
    const processData = (data) => {
      return data.map((item) => {
        // 在 classList 中查找匹配的 ID
        const matchedClass = mapping.value.find((cls) => cls.ID === item.ClassID); // 确保类型匹配

        // console.log("查看方法内打印的值: ", classList.value);

        return {
          ...item,
          Class: matchedClass ? matchedClass.Class : "未知分类", // 如果匹配则赋值，否则用默认值
        };
      });
    };
    // 将树结构数据转换成级联选择器要展示的数据
    const transformData = (data) => {
      return data.map(item => ({
        value: item.ID,
        label: item.Class,
        children: item.children && item.children.length ? transformData(item.children) : []
      }));
    };

    const dialogClass = ref(false);
    const editClass = () => {
      dialogClass.value = true;
    }
    const openDialogClass = () => {
      dialogClass.value = true;
    };
    const closeDialogClass = () => {
      dialogClass.value = false;
    };
    return {
      Action,
      treeData,
      defaultProps,
      searchForm,
      dialogForm,
      tableData,
      pageNum,
      pageSize,
      total,
      dialogVisible,
      classList,
      shortcuts,
      UserID,
      UUID,
      parseTime,
      handleNodeClick,
      searchData,
      reset,
      handleSizeChange,
      handleCurrentChange,
      formatClassName,
      openDialog,
      closeDialog,
      submitDialog,
      handleAdd,
      handleEdit,
      handleDelete,
      handlePreview,
      color,
      editClass,
      dialogClass,
      openDialogClass,
      closeDialogClass,
      GetUserChatCollectClass
    };
  },
});
</script>

<style scoped>
.main-container {
  height: calc(100vh - 70px);
  margin: 10px;
}

.aside {
  background-color: #fff;
}

.content-container {
  background-color: #fff;
  margin-left: 10px;
  width: calc(100vw - 325px);
}

.header {
  text-align: right;
  font-size: 12px;
  background-color: #fff;
  padding: 0 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  display: flex;
  align-items: center;
}

.input {
  width: 200px;
  margin-right: 10px;
  margin-left: 10px;
}

.checkbox {
  margin-right: 10px;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table {
  width: 100%;
  margin-bottom: 20px;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  background-color: #959595;
  border-radius: 50%;
  margin-right: 6px;
}

.count {
  color: #666;
  margin-left: 20px;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.custom-tooltip) {
  max-width: 800px !important;
  font-size: 14px;
}

:deep(.el-tabs__header ) {
  margin-left: 20px !important;
}
</style>

